const express = require('express');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const { body, validationResult } = require('express-validator');
const { query, transaction } = require('../config/database');
const { isValidEmail, isValidPassword, generateVerificationCode } = require('../utils/helpers');
const { authenticateToken } = require('../middleware/auth');
const emailService = require('../services/emailService');
const configService = require('../services/configService');

const router = express.Router();

// 用户注册
router.post('/register', [
  body('username').isLength({ min: 3, max: 50 }).withMessage('用户名长度必须在3-50个字符之间'),
  body('email').isEmail().withMessage('请输入有效的邮箱地址'),
  body('password').isLength({ min: 8 }).withMessage('密码长度至少8位')
], async (req, res) => {
  try {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ message: errors.array()[0].msg });
    }

    const { username, email, password } = req.body;

    // 验证邮箱格式
    if (!isValidEmail(email)) {
      return res.status(400).json({ message: '邮箱格式不正确' });
    }

    // 验证密码强度
    if (!isValidPassword(password)) {
      return res.status(400).json({ message: '密码必须包含字母和数字，长度至少8位' });
    }

    // 检查用户是否已存在
    const existingUser = await query(
      'SELECT id FROM users WHERE username = ? OR email = ?',
      [username, email]
    );

    if (existingUser.length > 0) {
      return res.status(400).json({ message: '用户名或邮箱已存在' });
    }

    // 生成验证码
    const verificationCode = generateVerificationCode();
    const expiresAt = new Date(Date.now() + 5 * 60 * 1000); // 5分钟后过期

    await transaction(async (connection) => {
      // 加密密码
      const passwordHash = await bcrypt.hash(password, 12);

      // 创建用户
      const [result] = await connection.execute(
        'INSERT INTO users (username, email, password_hash) VALUES (?, ?, ?)',
        [username, email, passwordHash]
      );

      // 保存验证码
      await connection.execute(
        'INSERT INTO email_verifications (email, code, type, expires_at) VALUES (?, ?, ?, ?)',
        [email, verificationCode, 'register', expiresAt]
      );

      // 发送验证邮件
      await emailService.sendVerificationEmail(email, verificationCode, 'register');
    });

    res.status(201).json({ 
      message: '注册成功，请查收邮箱验证码完成验证' 
    });

  } catch (error) {
    console.error('注册错误:', error);
    res.status(500).json({ message: '注册失败，请稍后重试' });
  }
});

// 验证邮箱
router.post('/verify-email', [
  body('email').isEmail().withMessage('请输入有效的邮箱地址'),
  body('code').isLength({ min: 6, max: 6 }).withMessage('验证码必须是6位数字')
], async (req, res) => {
  try {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ message: errors.array()[0].msg });
    }

    const { email, code } = req.body;

    // 验证验证码
    const verification = await query(
      'SELECT * FROM email_verifications WHERE email = ? AND code = ? AND type = ? AND expires_at > NOW() AND is_used = FALSE',
      [email, code, 'register']
    );

    if (verification.length === 0) {
      return res.status(400).json({ message: '验证码无效或已过期' });
    }

    await transaction(async (connection) => {
      // 更新用户验证状态
      await connection.execute(
        'UPDATE users SET is_verified = TRUE WHERE email = ?',
        [email]
      );

      // 标记验证码为已使用
      await connection.execute(
        'UPDATE email_verifications SET is_used = TRUE WHERE id = ?',
        [verification[0].id]
      );
    });

    res.json({ message: '邮箱验证成功' });

  } catch (error) {
    console.error('邮箱验证错误:', error);
    res.status(500).json({ message: '验证失败，请稍后重试' });
  }
});

// 用户登录
router.post('/login', [
  body('login').notEmpty().withMessage('请输入用户名或邮箱'),
  body('password').notEmpty().withMessage('请输入密码')
], async (req, res) => {
  try {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ message: errors.array()[0].msg });
    }

    const { login, password } = req.body;

    // 查找用户（支持用户名或邮箱登录）
    const user = await query(
      'SELECT id, username, email, password_hash, is_active, is_verified FROM users WHERE (username = ? OR email = ?) AND is_active = TRUE',
      [login, login]
    );

    if (user.length === 0) {
      return res.status(401).json({ message: '用户名或密码错误' });
    }

    const userData = user[0];

    // 验证密码
    const isValidPassword = await bcrypt.compare(password, userData.password_hash);
    if (!isValidPassword) {
      return res.status(401).json({ message: '用户名或密码错误' });
    }

    // 检查邮箱是否已验证
    if (!userData.is_verified) {
      return res.status(401).json({ message: '请先验证邮箱' });
    }

    // 生成JWT令牌
    const jwtConfig = await configService.getJWTConfig();
    const token = jwt.sign(
      { userId: userData.id, username: userData.username },
      jwtConfig.secret,
      { expiresIn: jwtConfig.expiresIn }
    );

    // 更新最后登录时间
    await query(
      'UPDATE users SET last_login_at = NOW() WHERE id = ?',
      [userData.id]
    );

    res.json({
      message: '登录成功',
      token,
      user: {
        id: userData.id,
        username: userData.username,
        email: userData.email
      }
    });

  } catch (error) {
    console.error('登录错误:', error);
    res.status(500).json({ message: '登录失败，请稍后重试' });
  }
});

// 邮箱验证码登录
router.post('/login-with-code', [
  body('email').isEmail().withMessage('请输入有效的邮箱地址'),
  body('code').isLength({ min: 6, max: 6 }).withMessage('验证码必须是6位数字')
], async (req, res) => {
  try {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ message: errors.array()[0].msg });
    }

    const { email, code } = req.body;

    // 验证验证码（支持login和register类型）
    const verification = await query(
      'SELECT * FROM email_verifications WHERE email = ? AND code = ? AND type IN (?, ?) AND expires_at > NOW() AND is_used = FALSE',
      [email, code, 'login', 'register']
    );

    if (verification.length === 0) {
      return res.status(400).json({ message: '验证码无效或已过期' });
    }

    // 查找用户
    const user = await query(
      'SELECT id, username, email, is_active FROM users WHERE email = ? AND is_active = TRUE',
      [email]
    );

    // 如果是register类型的验证码且用户不存在，返回新用户标识
    if (verification[0].type === 'register' && user.length === 0) {
      // 标记验证码为已使用
      await query(
        'UPDATE email_verifications SET is_used = TRUE WHERE id = ?',
        [verification[0].id]
      );

      res.json({
        message: '验证码验证成功，请完善您的信息',
        isNewUser: true,
        email: email
      });
      return;
    }

    if (user.length === 0) {
      return res.status(401).json({ message: '用户不存在' });
    }

    const userData = user[0];

    await transaction(async (connection) => {
      // 生成JWT令牌
      const jwtConfig = await configService.getJWTConfig();
      const token = jwt.sign(
        { userId: userData.id, username: userData.username },
        jwtConfig.secret,
        { expiresIn: jwtConfig.expiresIn }
      );

      // 更新最后登录时间
      await connection.execute(
        'UPDATE users SET last_login_at = NOW() WHERE id = ?',
        [userData.id]
      );

      // 标记验证码为已使用
      await connection.execute(
        'UPDATE email_verifications SET is_used = TRUE WHERE id = ?',
        [verification[0].id]
      );

      res.json({
        message: '登录成功',
        token,
        user: {
          id: userData.id,
          username: userData.username,
          email: userData.email
        },
        isNewUser: false
      });
    });

  } catch (error) {
    console.error('验证码登录错误:', error);
    res.status(500).json({ message: '登录失败，请稍后重试' });
  }
});

// 验证token
router.get('/verify', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;
    const user = await query(
      'SELECT id, username, email, avatar, grade, major, dream_career, bio FROM users WHERE id = ? AND is_active = TRUE',
      [userId]
    );
    
    if (user.length === 0) {
      return res.status(401).json({ message: '用户不存在或已被禁用' });
    }
    
    const userData = user[0];
    res.json({
      message: 'Token验证成功',
      user: userData
    });
  } catch (error) {
    console.error('Token验证错误:', error);
    res.status(500).json({ message: 'Token验证失败' });
  }
});

// 发送登录验证码
router.post('/send-login-code', [
  body('email').isEmail().withMessage('请输入有效的邮箱地址')
], async (req, res) => {
  try {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ message: errors.array()[0].msg });
    }

    const { email } = req.body;

    // 检查是否在10秒内已经发送过验证码
    const recentCode = await query(
      'SELECT created_at FROM email_verifications WHERE email = ? AND created_at > DATE_SUB(NOW(), INTERVAL 10 SECOND) ORDER BY created_at DESC LIMIT 1',
      [email]
    );

    if (recentCode.length > 0) {
      const timeLeft = Math.ceil((10 - (Date.now() - new Date(recentCode[0].created_at)) / 1000));
      return res.status(429).json({ 
        message: `请等待 ${timeLeft} 秒后再获取验证码`,
        timeLeft: timeLeft
      });
    }

    // 检查用户是否存在
    const user = await query(
      'SELECT id FROM users WHERE email = ? AND is_active = TRUE',
      [email]
    );

    // 确定验证码类型
    const codeType = user.length > 0 ? 'login' : 'register';

    // 生成验证码
    const verificationCode = generateVerificationCode();
    const expiresAt = new Date(Date.now() + 5 * 60 * 1000); // 5分钟后过期

    // 保存验证码
    await query(
      'INSERT INTO email_verifications (email, code, type, expires_at) VALUES (?, ?, ?, ?)',
      [email, verificationCode, codeType, expiresAt]
    );

    // 发送验证邮件
    await emailService.sendVerificationEmail(email, verificationCode, codeType);

    res.json({ 
      message: '验证码已发送，请查收邮箱',
      type: codeType 
    });

  } catch (error) {
    console.error('发送验证码错误:', error);
    res.status(500).json({ message: '发送失败，请稍后重试' });
  }
});

module.exports = router;
